//################################
// 版权所有：鸽子游戏俱乐部
// 系统名称：鸽子游戏俱乐部-移动版
// 文件名称：firstpageRent.js
// 创建时间：2017年04月30日
// 创建人员：Lemo
// 功能说明：firstpage rent page
//################################

'use strict';

import React, {Component, PropTypes} from 'react';
import {
    StyleSheet,
    Text,
    View,
    ListView,
    Dimensions,
    Image,
    ActivityIndicator,
    TouchableOpacity,
    TouchableHighlight,
    InteractionManager,
} from 'react-native';

import {
    UIConstants,
    Colors,
    FontSizes,
    CommonData,
    CommonFunc,
    Routes,
} from '../../common';

import Images from '../../images';
import * as ActionTypes from '../../actions/types';
import RectButton from '../../components/rectbutton';
import GiftedListView from '../../components/pandaListView';
import {toastTip} from '../../utils/toastTipUtil';
import FirstPageGameDetailContainer from '../containers/firstPageGameDetailContainer';
import FirstPageGameDetailWebContainer from './firstPageGameDetailWeb';
import {getGameList} from '../../actions';

const WINDOW_WIDTH = Dimensions.get('window').width;
const COUNT = 10;   //每页条数
var borderColor = '#EAEAEA';

class FirstPageRent extends Component {
    
    constructor(props) {
        super(props);

        //租借列表
        this.renderRow = this.renderRowFunc.bind(this);
        this.onFetch = this.onFetchFunc.bind(this);
        this.renderPaginationFetchigView = this.renderPaginationFetchigViewFunc.bind(this);
        this.renderPaginationAllLoadedView = this.renderPaginationAllLoadedViewFunc.bind(this);
        this.renderPaginationWaitingView = this.renderPaginationWaitingViewFunc.bind(this);
        this.renderEmptyView = this.renderEmptyViewFunc.bind(this);

        this.onTitlePress = this.onTitlePressFunc.bind(this);
        this.onRectButtonPress = this.onRectButtonPressFunc.bind(this);

        this.changeTab = false;     //是否切换了游戏平台类型
        this.gametype = this.props.gameType;

    }

    componentDidMount() {
    }

    componentWillReceiveProps(nextProps) {
        switch (nextProps.actionType) {
            case ActionTypes.FIRSTPAGE_RENTLIST_SUCCESS:
                this._getListSuccess(nextProps.gamelist);
                break;
            case ActionTypes.FIRSTPAGE_RENTLIST_FAILED:
                this.listView && this.listView._updateRows(null);
                this.errorHandler(nextProps.gamelisterrormsg);
                break;
            default:
                break;
        }
    }

    onTitlePressFunc(title) {
        const {navigatorRoot} = this.props;
        InteractionManager.runAfterInteractions(()=>{
            navigatorRoot.push({
                name: Routes.FIRST_GAMEDETAIL,
                component: FirstPageGameDetailWebContainer,
                friend: true,
            });
        });
    }

    onRectButtonPressFunc(id) {
        // alert("id: "+id);
    }

    renderRowFunc(rowData) {
        return (
            <View style={styles.itemrow}>
                <RectButton 
                    icon={Images.cover001} 
                    iteminfo={rowData} 
                    onPressItem={this.onRectButtonPress} 
                    onPressTitle={this.onTitlePress}
                />
            </View>
        );
    }

    onFetchFunc(page = 1, callback, options) {
        this.callback = callback;
        this.currentPageNum = page;
        setTimeout(() => {
            const {dispatch} = this.props;
            dispatch(getGameList(this.props.gameType, page, COUNT));
        }, 300);
    }

    renderPaginationFetchigViewFunc() {
        return (
            <View style={customStyles.defaultView}>
                <ActivityIndicator
                    animating={true}
                    style={{height: 80,marginTop:50}}
                    color="#37B9D0"
                    size="large"
                />
            </View>
        );
    }
    
	renderPaginationAllLoadedViewFunc() {
		return (
		    <View style={customStyles.paginationView}>
				<Text style={[customStyles.actionsLabel, {fontSize:14}]}>
                    {'无更多数据'}
				</Text>
			</View>
		);
  	}
    
    renderPaginationWaitingViewFunc(paginateCallback) {
		return (
			<TouchableHighlight
				underlayColor='#EAEAEA'
				onPress={paginateCallback}
				style={customStyles.paginationView}>
				<Text style={[customStyles.actionsLabel, {fontSize:14}]}>
					{'加载更多'}
				</Text>
			</TouchableHighlight>
		);
  	}
    
    renderEmptyViewFunc(refreshCallback) {
        return (
            <View style={customStyles.defaultView}>
                <Text style={customStyles.defaultViewTitle}>
                    {'暂无数据'}
                </Text>
            </View>
        );
    }
    
    _getListSuccess(listdata) {
        let newList = listdata.data;
        if (CommonFunc.isEmpty(newList)) {
            if (this.changeTab) {
                this.callback && this.callback([]);
            } else {
                this.callback && this.callback([], {allLoaded: true});
            }
        } else {
            let isAllLoaded = false;
            if (this.currentPageNum === listdata.pageCount) {
                isAllLoaded = true;
            }
            if (this.currentPageNum === 1) {
                this.listView._updateRows(newList, {allLoaded: isAllLoaded});
            } else {
                this.callback && this.callback(newList, {allLoaded: isAllLoaded});
            }
        }

        if (this.changeTab) {
            this.listView.refs.listview.scrollTo({x: 0, y: 0, animated: true,});
            this.listView.refs.listview.scrollTo({x: 0, y: 0, animated: true,});
            this.changeTab = false;
        }
    }

    errorHandler(msg) {
        toastTip(msg, 'long');
    }

    onChangeTypeFunc() {
        this.changeTab = true;
        this.currentPageNum = 1;
        this.gametype = this.props.gameType;
        //刷新GiftedListView，自动调onFetch方法获取第一页数据
        this.listView && this.listView._onRefresh({external: true});
    }

    render() {
        if (this.gametype !== this.props.gameType) {
            this.onChangeTypeFunc();
        }
        return (
            <View style={styles.container}>
                <GiftedListView
                    ref={(ref) => {this.listView = ref}}
                    rowView={this.renderRow}
                    onFetch={this.onFetch}
                    contentContainerStyle={styles.list}
                    initialListSize={10} // the maximum number of rows displayable without scrolling (height of the listview / height of row)
                    firstLoader={true} // display a loader for the first fetching
                    pagination={true} // enable infinite scrolling using touch to load more
                    paginationFetchingView={this.renderPaginationFetchigView}
                    paginationAllLoadedView={this.renderPaginationAllLoadedView}
                    paginationWaitingView={this.renderPaginationWaitingView}
                    refreshable={true} // enable pull-to-refresh for iOS and touch-to-refresh for Android
                    emptyView={this.renderEmptyView}
                />
            </View>
        );
    }
}

var customStyles = {
    separator: {
        backgroundColor: '#CCC',
        height: 1,
    },
    refreshableView: {
        height: 50,
        backgroundColor: '#fff',
        justifyContent: 'center',
        alignItems: 'center',
    },
    actionsLabel: {
        fontSize: 20,
        color: '#007aff',
    },
    paginationView: {
        width: WINDOW_WIDTH,
        height: 44,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#FFF',
    },
    defaultView: {
        width: WINDOW_WIDTH,
        justifyContent: 'center',
        alignItems: 'center',
        padding: 20,
    },
    defaultViewTitle: {
        fontSize: 16,
        fontWeight: 'bold',
        marginBottom: 15,
    },
    emptybutton: {
        flex: 1, 
        width: 100, 
        alignItems: 'center',
    },
    emptybuttontext: {
        flex: 1, 
        textAlign: 'center', 
        marginTop: 10, 
        marginBottom: 10, 
        color: Colors.green, 
        fontSize: 16
    },
    row: {
        padding: 10,
        height: 44,
    },
    header: {
        backgroundColor: '#50a4ff',
        padding: 10,
    },
    headerTitle: {
        color: '#fff',
    }
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: Colors.appBackground,
    },
    itemrow: {
        width: (WINDOW_WIDTH-18)/2,
        marginLeft:5,
        marginTop: 5,
        
    },
    renderrowimage: {
        width: 60,
        height: 85,
        margin: 3,
    },
    renderrowtext: {
        marginLeft: 5,
        fontSize: 10,
    },
    list: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        paddingBottom: 5,
    }
});

export default FirstPageRent;